package org.yjc.controller;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yjc.custom.DateUtils;
import org.yjc.custom.JqgridParam;
import org.yjc.custom.JqgridUtils;
import org.yjc.entity.KingRoot;
import org.yjc.entity.Lessee;
import org.yjc.entity.SysUser;
import org.yjc.form.KingRootForm;
import org.yjc.service.KingRootService;
import org.yjc.service.LesseeAdminService;
import org.yjc.service.LesseeService;

@Controller
@RequestMapping(value="/lesseekingroot")
public class LesseeKingRootController {
	@Autowired
	private LesseeAdminService lesseeadminservice;
	@Autowired
	private KingRootService kingrootservice;
	@Autowired
	private LesseeService lesseeservice;
	
	@RequestMapping(value="/lesseekingroot")
	public String alllessee(ModelMap map) {
		SysUser sysuser = new SysUser();
		//获取上下文对象
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username = userDetails.getUsername();
		sysuser = lesseeadminservice.findByUsername(username);
		Integer id = sysuser.getId(); //获取到当前租户管理员的id
		List<Lessee> lessees = lesseeservice.findByLesseeadminId(id); //通过id查询该租户管理员的下级租户
		
		Integer lesseeid = 0;
		if(!lessees.isEmpty()) {
			lesseeid = lessees.get(0).getId();
		} //取每一个租户的id
		map.put("lessees",lessees);
		map.put("lesseeid",lesseeid);
		return "lesseekingroot/lesseekingroot";
	}
	
	@RequestMapping(value="list")
	@ResponseBody
	public Object list(JqgridParam param,Integer lesseeId) {
		Pageable pageable = param.buildPageable();
		Specification spec = new Specification<KingRoot>() {

			@Override
			public Predicate toPredicate(Root<KingRoot> root, CriteriaQuery<?> arg1, CriteriaBuilder cb) {
				Predicate predicate = cb.equal(root.get("lessee").get("id"), lesseeId);
				return predicate;
			}
		};
		Page<KingRoot> page;
		if (param.getSearch()) {
			spec = spec.and(param.buildSpec());
		}
		page = kingrootservice.findAll(spec, pageable);
		return JqgridUtils.getPageResult(page);
	}
}
